# # # from datetime import datetime, timezone, timedelta
# # #
# # # timestamp_ms = 1752110846000
# # # dt = datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone(timedelta(hours=8)))
# # # print(dt.strftime('%Y-%m-%d %H:%M:%S'))
# # def main(data: str) -> dict:
# #     def format_block(title, stats):
# #         mapping = {
# #             "warn": "报警（warn）",
# #             "fault": "故障（fault）",
# #             "timeout": "超时（timeout）",
# #             "shutdown": "关机（shutdown）",
# #             "weekwc": "本周完成校准（weekwc）",
# #             "weekwwc": "本周未完成校准（weekwwc）",
# #             "monthwc": "本月完成校准（monthwc）",
# #             "monthwwc": "本月未完成校准（monthwwc）",
# #         }
# #         lines = [f"【{title}】"]
# #         for key in mapping:
# #             value = stats.get(key, 0)
# #             lines.append(f"- {mapping[key]}：{value}")
# #         return "\n".join(lines)
# #
# #     radar_data = data.get("query_station_radar_alarm_count", {})
# #     ground_data = data.get("query_station_ground_alarm_count", {})
# #
# #     radar_block = format_block("雷达站报警统计", radar_data)
# #     ground_block = format_block("地面站报警统计", ground_data)
# #
# #     return {
# #         "radar_block":radar_block,
# #         "ground_block":ground_block
# #     }
# # test_data = {
# #     "query_station_radar_alarm_count": {
# #         "warn": 0, "fault": 2, "monthwc": 7, "timeout": 2,
# #         "shutdown": 1, "weekwc": 4, "weekwwc": 6, "monthwwc": 3
# #     },
# #     "query_station_ground_alarm_count": {
# #         "warn": 9, "fault": 5, "monthwc": 402, "timeout": 6,
# #         "shutdown": 1, "weekwc": 70, "weekwwc": 0, "monthwwc": 30
# #     }
# # }
# #
# # print(main(test_data))
# #
#
# import json  # 标准库，无需额外安装
#
# def format_alarm_stats(data: str) -> dict:
#     try:
#         parsed = json.loads(data)
#     except Exception as e:
#         return {
#             "radar_block": f"❌ 解析 JSON 字符串失败：{e}",
#             "ground_block": ""
#         }
#
#     def format_block(title, stats):
#         mapping = {
#             "warn": "报警（warn）",
#             "fault": "故障（fault）",
#             "timeout": "超时（timeout）",
#             "shutdown": "关机（shutdown）",
#             "weekwc": "本周完成校准（weekwc）",
#             "weekwwc": "本周未完成校准（weekwwc）",
#             "monthwc": "本月完成校准（monthwc）",
#             "monthwwc": "本月未完成校准（monthwwc）",
#         }
#         lines = [f"【{title}】"]
#         for key in mapping:
#             value = stats.get(key, 0)
#             lines.append(f"- {mapping[key]}：{value}")
#         return "\n".join(lines)
#
#     radar_data = parsed.get("query_station_radar_alarm_count", {})
#     ground_data = parsed.get("query_station_ground_alarm_count", {})
#
#     return {
#         "radar_block": format_block("雷达站报警统计", radar_data),
#         "ground_block": format_block("地面站报警统计", ground_data)
#     }
# input_data = "{\"query_station_radar_alarm_count\": {\"warn\": 0, \"fault\": 2, \"monthwc\": 7, \"timeout\": 2, \"shutdown\": 1, \"weekwc\": 4, \"weekwwc\": 6, \"monthwwc\": 3}, \"query_station_ground_alarm_count\": {\"warn\": 9, \"fault\": 5, \"monthwc\": 402, \"timeout\": 6, \"shutdown\": 1, \"weekwc\": 70, \"weekwwc\": 0, \"monthwwc\": 30}}"
#
# result = format_alarm_stats(input_data)
# print(result)
import json

def main(data: str) -> dict:
    try:
        parsed = json.loads(data)
    except Exception as e:
        return {
            "detection_block": f"❌ JSON 解析失败：{e}",
            "count_block": ""
        }

    # 提取字段
    detection_list = parsed.get("query_station_area_detection", {}).get("data", [])
    count_info = parsed.get("query_station_area_detection_count", {}).get("data", {}).get("data", {})

    # 格式化入侵事件列表
    detection_lines = ["【区域入侵检测列表】"]
    for i, item in enumerate(detection_list, 1):
        reason = item.get("reason", "")
        # 处理为真实中文（部分是 JSON 格式的字符串）
        try:
            reason_list = json.loads(reason)
            reason_str = "，".join(reason_list)
        except:
            reason_str = reason
        detection_lines.append(
            f"{i}. 站点：{item.get('stationName', '')}，设备：{item.get('eqName', '')}，等级：{item.get('level', '')}，"
            f"时间：{item.get('startTime', '')}，原因：{reason_str}，图片：{item.get('url', '')}"
        )

    # 格式化统计块
    count_lines = [
        "【区域入侵检测统计】",
        f"- 年累计次数（yrcount）：{count_info.get('yrcount', 0)}",
        f"- 当前次数（count）：{count_info.get('count', 0)}",
        f"- 累计落点次数（ldcount）：{count_info.get('ldcount', 0)}"
    ]

    return {
        "detection_block": "\n".join(detection_lines),
        "count_block": "\n".join(count_lines)
    }
